﻿// 引入相关命名空间
using BUGCOME.Infrastructure.Attribute;
using BUGCOME.Infrastructure.Extensions;
using BUGCOME.Model.Auth;
using BUGCOME.Model.Auth.dto;
using BUGCOME.Model.Logs;
using BUGCOME.Repository;
using BUGCOME.Service.Auth.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BUGCOME.Service.Auth
{
    /// <summary>
    /// 用户在线时长Service业务层处理
    /// </summary>
    // 注册服务，实现IUserOnlineLogService接口，生命周期为瞬时
    [AppService(ServiceType = typeof(IUserOnlineLogService), ServiceLifetime = LifeTime.Transient)]
    public class UserOnlineLogService : BaseService<UserOnlineLog>, IUserOnlineLogService
    {
        /// <summary>
        /// 添加用户在线日志
        /// </summary>
        /// <param name="model">日志模型</param>
        /// <param name="user">在线用户信息</param>
        /// <returns>添加后的日志模型</returns>
        public async Task<UserOnlineLog> AddUserOnlineLogAsync(UserOnlineLog model, OnlineUsers user)
        {
            // 赋值用户信息到日志模型
            model.UserId = user.Userid;
            model.Location = user?.Location;
            model.OnlineTime = user.OnlineTime;
            model.UserIP = user.UserIP;
            model.Platform = user.Platform;
            model.Remark = user.Browser;
            model.LoginTime = user.LoginTime;
            model.AddTime = DateTime.Now;
            // 在线时长>=0.5时插入数据库
            if (model.OnlineTime >= 0.5)
            {
                await Insertable(model).ExecuteReturnSnowflakeIdAsync();
            }
            return model;
        }

        /// <summary>
        /// 导出用户在线日志列表（分页）
        /// </summary>
        /// <param name="parm">查询参数</param>
        /// <returns>分页的日志DTO列表</returns>
        public async Task<PagedInfo<UserOnlineLogDto>> ExportListAsync(UserOnlineLogQueryDto parm)
        {
            // 获取查询表达式
            var predicate = QueryExp(parm);

            // 执行查询并转换为分页DTO
            var response = await Queryable()
                .Where(predicate.ToExpression())
                .Select((it) => new UserOnlineLogDto(), true)
                .ToPageAsync(parm);

            return response;
        }

        /// <summary>
        /// 获取用户在线日志列表（分页）
        /// </summary>
        /// <param name="parm">查询参数</param>
        /// <returns>分页的日志DTO列表</returns>
        public async Task<PagedInfo<UserOnlineLogDto>> GetListAsync(UserOnlineLogQueryDto parm)
        {
            // 获取查询表达式
            var predicate = QueryExp(parm);

            // 关联用户表查询并转换为分页DTO
            var response = await Queryable()
                .Where(predicate.ToExpression())
                .LeftJoin<UserBase>((it, u) => it.UserId == u.Id)
                .Select((it, u) => new UserOnlineLogDto() { NickName = u.NickName }, true)
                .ToPageAsync(parm);

            return response;
        }

        /// <summary>
        /// 构建查询表达式
        /// </summary>
        /// <param name="parm">查询参数</param>
        /// <returns>查询表达式</returns>
        private static Expressionable<UserOnlineLog> QueryExp(UserOnlineLogQueryDto parm)
        {
            var predicate = Expressionable.Create<UserOnlineLog>();

            // 根据参数动态构建查询条件
            predicate = predicate.AndIF(parm.UserId != null, it => it.UserId == parm.UserId);
            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.UserIP), it => it.UserIP == parm.UserIP);
            predicate = predicate.AndIF(parm.BeginAddTime == null, it => it.AddTime >= DateTime.Now.ToShortDateString().ParseToDateTime());
            predicate = predicate.AndIF(parm.BeginAddTime != null, it => it.AddTime >= parm.BeginAddTime);
            return predicate;
        }
    }
}